package com.doge.calcalbum.business.calc

import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.constraintlayout.widget.ConstraintLayout
import com.doge.calcalbum.utils.appContext
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit

class LongTouchLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : ConstraintLayout(context, attrs) {
    interface Callback {
        fun invoke()
    }
    private var downTimestamp = 0L
    private var longTask: Disposable? = null
    private var callback: Callback? = null

    fun setCallback(listener: Callback) {
        callback = listener
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        when(ev?.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                downTimestamp = System.currentTimeMillis()
                longTask?.dispose()
                longTask = Observable.timer(6000L, TimeUnit.MILLISECONDS)
                    .doOnNext { callback() }
                    .subscribe()
            }
            MotionEvent.ACTION_UP -> {
                longTask?.dispose()
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun callback() {
        val vibrator = appContext.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val effect = VibrationEffect.createWaveform(longArrayOf(300L, 300L), -1)
            vibrator.vibrate(effect)
        } else {
            vibrator.vibrate(longArrayOf(300L, 300L), -1)
        }
        callback?.invoke()
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        longTask?.dispose()
    }
}